﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Aribaccio.Office
{
    public class OfficerBatch
    {
        /// <summary>
        /// 状态
        /// </summary>
        private Result DataStatus;
        /// <summary>
        /// 定期工作任务操作线程
        /// </summary>
        private PeriodicTaskManual JobTask;
        /// <summary>
        /// 写入文件操作辅助对象
        /// </summary>
        private IOfficer OfficeHelper;
        /// <summary>
        /// 执行存储分页数据的队列
        /// </summary>
        private ConcurrentQueue<OfficeFileData> OfficeFileDataQueue = new ConcurrentQueue<OfficeFileData>();

        /// <summary>
        /// 带参构造函数
        /// </summary>
        /// <param name="argOfficeHelper"></param>
        public OfficerBatch(IOfficer argOfficeHelper)
        {
            this.OfficeHelper = argOfficeHelper;
            this.DataStatus = new Result(ResultStatus.Failure);
            this.JobTask = new PeriodicTaskManual($"批次导出文件服务", 100, MonitorTaskAction, true, true);
        }
        /// <summary>
        /// 重置状态为默认状态
        /// </summary>
        public void ResetStatus()
        {
            this.DataStatus.ResultCode = ResultStatus.Failure;
        }
        /// <summary>
        /// 添加到队列
        /// </summary>
        /// <param name="argFileData"></param>
        public void QueueEnqueue(OfficeFileData argFileData)
        {
            if (argFileData == null) { return; }
            this.OfficeFileDataQueue.Enqueue(argFileData);
            this.ResetStatus();
        }
        /// <summary>
        /// 等待所有执行完成
        /// </summary>
        /// <returns></returns>
        public Task<Result> WaitReadStatus()
        {
            return Task.Run(() =>
            {
                while (true) { if (OfficeFileDataQueue.Count <= 0 && this.DataStatus.ResultState) { break; } }
                return this.DataStatus;
            });
        }
        /// <summary>
        /// 定期任务执行
        /// </summary>
        /// <returns></returns>
        protected void MonitorTaskAction()
        {
            if (OfficeFileDataQueue.Count <= 0) { return; }
            OfficeFileData? oFileData;
            if (OfficeFileDataQueue.TryDequeue(out oFileData))
            {
                if (oFileData == null) return;
                Task<Result> resultTask = this.OfficeHelper.WriteDataTableHead(oFileData.FilePathName, oFileData.DataTable, oFileData.IsCreateFile, oFileData.IsCreateColumns);
                Task.WaitAll(resultTask);
                if (OfficeFileDataQueue.Count <= 0)
                {
                    this.DataStatus.ResultCode = ResultStatus.Succeed;
                    if (resultTask != null && resultTask.Result != null) { this.DataStatus.ResultMilliseconds += resultTask.Result.ResultMilliseconds; }
                }
            }
        }
    }
}
